<template>
  <div class="space-y-4">
    <!-- 订单状态标签 -->
    <div class="flex space-x-2 mb-4">
      <button 
        v-for="tab in orderTabs" 
        :key="tab.key"
        @click="activeTab = tab.key"
        :class="[
          'px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200',
          activeTab === tab.key 
            ? 'bg-indigo-100 text-indigo-700 shadow-sm' 
            : 'text-gray-600 hover:bg-gray-100'
        ]"
      >
        {{ tab.label }}
        <span v-if="tab.count > 0" 
              :class="[
                'ml-2 px-2 py-0.5 rounded-full text-xs',
                activeTab === tab.key 
                  ? 'bg-indigo-200 text-indigo-800' 
                  : 'bg-gray-200 text-gray-600'
              ]">
          {{ tab.count }}
        </span>
      </button>
    </div>

    <!-- 订单列表 -->
    <div class="space-y-4">
      <div v-if="filteredOrders.length > 0">
        <div v-for="order in paginatedOrders" :key="order.id" 
             class="bg-white rounded-2xl shadow-sm hover:shadow-md transition-all duration-300 overflow-hidden border border-gray-100">
          
          <!-- 订单头部 -->
          <div class="p-4 border-b border-gray-50">
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-3">
                <div class="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-400 to-purple-500 flex items-center justify-center">
                  <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
                  </svg>
                </div>
                <div>
                  <h4 class="font-semibold text-gray-900">{{ order.storeName }}</h4>
                  <p class="text-sm text-gray-500">订单号: {{ order.orderNumber || order.id }}</p>
                </div>
              </div>
              <div class="text-right">
                <span :class="[
                  'inline-flex items-center px-3 py-1 rounded-full text-xs font-medium',
                  getStatusStyle(order.status)
                ]">
                  <span :class="['w-2 h-2 rounded-full mr-2', getStatusDotStyle(order.status)]"></span>
                  {{ order.status }}
                </span>
                <p class="text-sm text-gray-500 mt-1">{{ formatDate(order.createTime) }}</p>
              </div>
            </div>
          </div>

          <!-- 订单商品 -->
          <div class="p-4">
            <div class="space-y-3">
              <div v-for="item in order.items" :key="item.name" 
                   class="flex items-center space-x-3 p-3 bg-gray-50 rounded-xl">
                <div class="w-12 h-12 rounded-lg overflow-hidden bg-white shadow-sm">
                  <img v-if="item.image" :src="item.image" :alt="item.name" 
                       class="w-full h-full object-cover">
                  <div v-else class="w-full h-full bg-gradient-to-br from-gray-200 to-gray-300 flex items-center justify-center">
                    <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                    </svg>
                  </div>
                </div>
                <div class="flex-1">
                  <h5 class="font-medium text-gray-900 text-sm">{{ item.name }}</h5>
                  <p class="text-xs text-gray-500">数量: {{ item.quantity }}</p>
                </div>
                <div class="text-right">
                  <p class="font-semibold text-gray-900">¥{{ (item.price * item.quantity).toFixed(2) }}</p>
                  <p class="text-xs text-gray-500">¥{{ item.price }}/件</p>
                </div>
              </div>
            </div>

            <!-- 订单总计和操作 -->
            <div class="mt-4 pt-4 border-t border-gray-100">
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                  <button v-if="order.status === '配送中'" 
                          @click="trackOrder(order.id)"
                          class="text-indigo-600 hover:text-indigo-700 text-sm font-medium transition-colors">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    </svg>
                    追踪订单
                  </button>
                  <button v-if="order.status === '已完成'" 
                          @click="reviewOrder(order.id)"
                          class="text-green-600 hover:text-green-700 text-sm font-medium transition-colors">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                    </svg>
                    评价订单
                  </button>
                  <button @click="reorderItems(order)"
                          class="text-gray-600 hover:text-gray-700 text-sm font-medium transition-colors">
                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    再次购买
                  </button>
                </div>
                <div class="text-right">
                  <p class="text-sm text-gray-500">总计</p>
                  <p class="text-xl font-bold text-gray-900">¥{{ order.totalPrice.toFixed(2) }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="text-center py-12">
        <div class="w-20 h-20 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
          <svg class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
          </svg>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-2">暂无订单</h3>
        <p class="text-gray-500 text-sm mb-6">您还没有任何订单记录</p>
        <button class="bg-indigo-500 hover:bg-indigo-600 text-white px-6 py-2 rounded-xl font-medium transition-colors">
          去购物
        </button>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="filteredOrders.length > itemsPerPage" class="flex justify-center items-center space-x-4 pt-4">
      <button 
        @click="prevPage" 
        :disabled="currentPage === 1"
        class="p-2 rounded-xl bg-white shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
      >
        <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
      </button>
      
      <div class="flex items-center space-x-2">
        <span v-for="page in visiblePages" :key="page"
              @click="currentPage = page"
              :class="[
                'w-10 h-10 rounded-xl flex items-center justify-center text-sm font-medium cursor-pointer transition-all duration-200',
                currentPage === page 
                  ? 'bg-indigo-500 text-white shadow-md' 
                  : 'bg-white text-gray-600 hover:bg-gray-50 shadow-sm'
              ]">
          {{ page }}
        </span>
      </div>
      
      <button 
        @click="nextPage" 
        :disabled="currentPage === totalPages"
        class="p-2 rounded-xl bg-white shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
      >
        <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
        </svg>
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MyOrders',
  props: {
    orders: {
      type: Object,
      default: () => ({ ongoing: [], completed: [] })
    },
    itemsPerPage: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      currentPage: 1,
      activeTab: 'all'
    }
  },
  computed: {
    // 订单标签
    orderTabs() {
      const ongoing = this.orders.ongoing || [];
      const completed = this.orders.completed || [];
      const cancelled = this.allOrders.filter(order => order.status === '已取消');
      
      return [
        { key: 'all', label: '全部', count: this.allOrders.length },
        { key: 'ongoing', label: '进行中', count: ongoing.length },
        { key: 'completed', label: '已完成', count: completed.length },
        { key: 'cancelled', label: '已取消', count: cancelled.length }
      ];
    },

    // 合并所有订单并按时间降序排序
    allOrders() {
      const ongoing = this.orders.ongoing || [];
      const completed = this.orders.completed || [];
      const allOrders = [...ongoing, ...completed];
      
      return allOrders.sort((a, b) => {
        return new Date(b.createTime || 0) - new Date(a.createTime || 0);
      });
    },

    // 根据当前标签过滤订单
    filteredOrders() {
      switch (this.activeTab) {
        case 'ongoing':
          return this.orders.ongoing || [];
        case 'completed':
          return this.orders.completed || [];
        case 'cancelled':
          return this.allOrders.filter(order => order.status === '已取消');
        default:
          return this.allOrders;
      }
    },
    
    // 计算总页数
    totalPages() {
      return Math.max(1, Math.ceil(this.filteredOrders.length / this.itemsPerPage));
    },
    
    // 当前页应显示的订单
    paginatedOrders() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = startIndex + this.itemsPerPage;
      return this.filteredOrders.slice(startIndex, endIndex);
    },

    // 可见的页码
    visiblePages() {
      const pages = [];
      const total = this.totalPages;
      const current = this.currentPage;
      
      if (total <= 5) {
        for (let i = 1; i <= total; i++) {
          pages.push(i);
        }
      } else {
        if (current <= 3) {
          pages.push(1, 2, 3, 4, 5);
        } else if (current >= total - 2) {
          pages.push(total - 4, total - 3, total - 2, total - 1, total);
        } else {
          pages.push(current - 2, current - 1, current, current + 1, current + 2);
        }
      }
      
      return pages;
    }
  },
  watch: {
    activeTab() {
      this.currentPage = 1; // 切换标签时重置页码
    }
  },
  methods: {
    // 获取订单状态样式
    getStatusStyle(status) {
      switch (status) {
        case '配送中':
          return 'bg-blue-100 text-blue-800';
        case '已完成':
          return 'bg-green-100 text-green-800';
        case '已取消':
          return 'bg-red-100 text-red-800';
        case '待付款':
          return 'bg-yellow-100 text-yellow-800';
        default:
          return 'bg-gray-100 text-gray-800';
      }
    },

    // 获取状态指示点样式
    getStatusDotStyle(status) {
      switch (status) {
        case '配送中':
          return 'bg-blue-500';
        case '已完成':
          return 'bg-green-500';
        case '已取消':
          return 'bg-red-500';
        case '待付款':
          return 'bg-yellow-500';
        default:
          return 'bg-gray-500';
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未知时间';
      const date = new Date(dateString);
      const now = new Date();
      const diff = now - date;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (days === 0) {
        return '今天';
      } else if (days === 1) {
        return '昨天';
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return date.toLocaleDateString('zh-CN');
      }
    },
    
    // 前往上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    
    // 前往下一页
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },

    // 追踪订单
    trackOrder(orderId) {
      console.log('追踪订单:', orderId);
      // 这里可以打开订单追踪页面或模态框
    },

    // 评价订单
    reviewOrder(orderId) {
      console.log('评价订单:', orderId);
      // 这里可以打开评价页面或模态框
    },

    // 再次购买
    reorderItems(order) {
      console.log('再次购买:', order);
      // 这里可以将商品添加到购物车
      this.$emit('reorder', order);
    }
  }
}
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>